package com.bawei.module_mall.ui.goodsshow


import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.module_mall.R
import com.bawei.module_mall.databinding.ActivityGoodsShowBinding
import android.widget.TextView
import com.google.android.material.tabs.TabLayoutMediator
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.view.Gravity
import android.graphics.drawable.ColorDrawable
import android.util.Log
import androidx.constraintlayout.widget.ConstraintLayout
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.base.BaseApplication
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseActivity
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.blankj.utilcode.util.ToastUtils


/**
 * 我的橱窗页面
 */
@Route(path = Router.Ui.GOODS_SHOW_ACTIVITY)
class GoodsShowActivity : BaseActivity() {

    private val binding: ActivityGoodsShowBinding by lazy {
        ActivityGoodsShowBinding.inflate(layoutInflater)
    }

    private val tabTitles = listOf("我的", "推荐")
    private var tabCounts = mutableListOf(0, 0)
    private lateinit var fragments: List<Fragment>
    private lateinit var tabMediator: TabLayoutMediator
    private var popupWindow: PopupWindow? = null
    private var currentSortType: String = ""
    private var priceSortDesc: Boolean = true // true: 高到低, false: 低到高

    override fun getLayoutRootView(): View {
        return binding.root
    }

    override fun generatStatusBarColor(): Int {
        return android.graphics.Color.WHITE
    }


    override fun initEvent() {
        //顶部栏点击事件
        binding.topBar.ivBack.setOnClickListener {
            finish()
        }

        binding.topBar.ivAvatar.setOnClickListener {
            gotoUserProfile()
        }

        binding.topBar.tvKoubei.setOnClickListener {
            gotoKoubeiDetail()
        }

        binding.topBar.tvSales.setOnClickListener {
            gotoKoubeiDetail()
        }

        // 更多按钮弹窗
        binding.topBar.ivMore.setOnClickListener {
            showPopupMenu(it)
        }

        // 动态Tab区域的返回按钮
        binding.ivBack.setOnClickListener {
            Log.d("GoodsShowActivity", "initEvent: 点击事件")
            finish()
        }

        // 动态Tab区域的搜索按钮
        binding.ivSearch.setOnClickListener {
            ARouter.getInstance().build("/mall/GoodsSearchActivity").navigation()
        }
    }

    override fun initView() {

        binding.topBar.tvUsername.text = AuthMMKV.username ?: "未登录"
        // 初始TabLayout左对齐
        val params =
            binding.tabLayout.layoutParams as ConstraintLayout.LayoutParams

        params.startToStart = ConstraintLayout.LayoutParams.PARENT_ID

        params.endToEnd = ConstraintLayout.LayoutParams.UNSET

        binding.tabLayout.layoutParams = params

        // 确保AppBarLayout的滚动行为正确配置
        binding.appBarLayout.setExpanded(true, true)

        // 设置AppBarLayout的滚动行为，实现动态Tab布局效果
        binding.appBarLayout.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
            // 计算滚动进度 (0 = 完全展开, 1 = 完全折叠)
            val scrollProgress = -verticalOffset.toFloat() / appBarLayout.totalScrollRange

            // 当滚动超过50%时，开始显示动态Tab布局
            if (scrollProgress > 0.5f) {
                // 显示返回和搜索按钮
                if (binding.ivBack.visibility != View.VISIBLE) {
                    binding.ivBack.visibility = View.VISIBLE
                    binding.ivSearch.visibility = View.VISIBLE

                    // 动画显示按钮
                    binding.ivBack.animate()
                        .alpha(1f)
                        .setDuration(200)
                        .setInterpolator(AccelerateDecelerateInterpolator())
                        .start()

                    binding.ivSearch.animate()
                        .alpha(1f)
                        .setDuration(200)
                        .setInterpolator(AccelerateDecelerateInterpolator())
                        .start()

                    // 将Tab居中
                    val params = binding.tabLayout.layoutParams as ConstraintLayout.LayoutParams
                    params.startToStart = ConstraintLayout.LayoutParams.PARENT_ID
                    params.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID
                    binding.tabLayout.layoutParams = params

                    // 添加Tab移动动画
                    binding.tabLayout.animate()
                        .translationX(0f)
                        .setDuration(200)
                        .setInterpolator(AccelerateDecelerateInterpolator())
                        .start()
                }

            } else {
                // 隐藏返回按钮
                if (binding.ivBack.visibility == View.VISIBLE) {

                    binding.ivBack.animate()
                        .alpha(0f)
                        .setDuration(200)
                        .setInterpolator(AccelerateDecelerateInterpolator())
                        .withEndAction {
                            binding.ivBack.visibility = View.GONE
                        }.start()


                    // 将Tab靠左对齐
                    val params = binding.tabLayout.layoutParams as ConstraintLayout.LayoutParams
                    params.startToStart =ConstraintLayout.LayoutParams.PARENT_ID
                    params.endToEnd = ConstraintLayout.LayoutParams.UNSET
                    binding.tabLayout.layoutParams = params

                    // 添加Tab移动动画
                    binding.tabLayout.animate()
                        .translationX(0f)
                        .setDuration(200)
                        .setInterpolator(AccelerateDecelerateInterpolator())
                        .start()
                }
            }
        }

        // 一级Tab和ViewPager2
        val myFragment = MyGoodsShowFragment()
        val recommendFragment = GoodsRecommendFragment()
        fragments = listOf(myFragment, recommendFragment)

        binding.viewPager.adapter =
            object : androidx.viewpager2.adapter.FragmentStateAdapter(this) {
                override fun getItemCount() = fragments.size
                override fun createFragment(position: Int) = fragments[position]
            }

        // 设置Fragment的数据更新回调
        myFragment.onDataUpdated = {
            updateTabCounts()
        }
        recommendFragment.onDataUpdated = {
            updateTabCounts()
        }

        tabMediator = TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
            tab.customView = getTabView(position)
        }

        tabMediator.attach()

        // Tab切换监听，切换时刷新对应商品列表
        binding.tabLayout.addOnTabSelectedListener(object :
            com.google.android.material.tabs.TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: com.google.android.material.tabs.TabLayout.Tab) {
                binding.viewPager.currentItem = tab.position
                // 切换时刷新对应Fragment商品列表
                when (tab.position) {

                }
            }

            override fun onTabUnselected(tab: com.google.android.material.tabs.TabLayout.Tab) {}
            override fun onTabReselected(tab: com.google.android.material.tabs.TabLayout.Tab) {}
        })

        // 延迟更新tab数量，等待Fragment初始化完成
        binding.viewPager.post {
            updateTabCounts()
        }

        // ViewPager2页面切换监听，保持Tab同步
        binding.viewPager.registerOnPageChangeCallback(object :
            androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                binding.tabLayout.selectTab(binding.tabLayout.getTabAt(position))
                // 页面切换时刷新对应Fragment商品列表
                when (position) {
                    0 -> {
                        val frag = fragments[0] as? MyGoodsShowFragment
                        if (frag?.isReady() == true) frag.refreshData()
                    }

                    1 -> {
                        val frag = fragments[1] as? GoodsRecommendFragment
                        if (frag?.isReady() == true) frag.refreshData()
                    }
                }
            }
        })

        // 二级导航栏
        val sortTitles = listOf("综合排序", "销量", "上新时间", "价格")

        sortTitles.forEach { title ->
            binding.tabSort.addTab(binding.tabSort.newTab().setText(title))
        }

        binding.tabSort.getTabAt(0)?.select()


        // 排序Tab监听
        binding.tabSort.addOnTabSelectedListener(object :
            com.google.android.material.tabs.TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: com.google.android.material.tabs.TabLayout.Tab) {
                when (tab.position) {
                    0 -> { // 综合排序
                        currentSortType = ""
                        priceSortDesc = true
                        setPriceTabText()
                        notifySortChanged()
                    }

                    1 -> { // 销量
                        currentSortType = "soldNum"
                        priceSortDesc = true
                        setPriceTabText()
                        notifySortChanged()
                    }

                    2 -> { // 上新时间
                        currentSortType = "createTime"
                        priceSortDesc = true
                        setPriceTabText()
                        notifySortChanged()
                    }

                    3 -> { // 价格
                        priceSortDesc = !priceSortDesc
                        currentSortType = "price"
                        setPriceTabText()
                        notifySortChanged()
                    }
                }
            }

            override fun onTabUnselected(tab: com.google.android.material.tabs.TabLayout.Tab) {}
            override fun onTabReselected(tab: com.google.android.material.tabs.TabLayout.Tab) {
                if (tab.position == 3) {
                    priceSortDesc = !priceSortDesc
                    currentSortType = "price"
                    setPriceTabText()
                    notifySortChanged()
                }
            }
        })

    }

    // 自定义TabView，显示数量
    private fun getTabView(position: Int): View {
        val view = LayoutInflater.from(this).inflate(R.layout.tab_goods_show, null)
        val tvTitle = view.findViewById<TextView>(R.id.tvTabTitle)
        val tvCount = view.findViewById<TextView>(R.id.tvTabCount)
        tvTitle.text = tabTitles[position]

        val count = tabCounts[position]
        if (count > 0) {
            tvCount.text = count.toString()
            tvCount.visibility = View.VISIBLE
        } else {
            tvCount.visibility = View.GONE
        }

        return view
    }

    // 刷新Tab数量
    private fun updateTabCount(myCount: Int, recommendCount: Int) {
        tabCounts[0] = myCount
        tabCounts[1] = recommendCount
        for (i in 0..1) {
            val tab = binding.tabLayout.getTabAt(i)
            tab?.customView = getTabView(i)
        }
    }

    // 从Fragment获取实际数据并更新tab数量
    private fun updateTabCounts() {
        val myCount = (fragments[0] as? MyGoodsShowFragment)?.getGoodsCount() ?: 0
        val recommendCount = (fragments[1] as? GoodsRecommendFragment)?.getGoodsCount() ?: 0

        updateTabCount(myCount, recommendCount)
    }

    // 气泡弹窗
    private fun showPopupMenu(anchor: View) {
        if (popupWindow == null) {
            val contentView =
                LayoutInflater.from(this).inflate(R.layout.popup_goods_show_menu, null)
            popupWindow = PopupWindow(
                contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                true
            )
            popupWindow?.setBackgroundDrawable(ColorDrawable(0x00000000))
            contentView.findViewById<LinearLayout>(R.id.llOrder).setOnClickListener {
                ToastUtils.showShort("我的订单")
                popupWindow?.dismiss()
            }
            contentView.findViewById<LinearLayout>(R.id.llShare).setOnClickListener {
                ToastUtils.showShort("分享")
                popupWindow?.dismiss()
            }
        }
        popupWindow?.showAsDropDown(anchor, -80, 0, Gravity.END)
    }

    private fun gotoUserProfile() {
        // TODO: 跳转个人主页
        ToastUtils.showShort("进入个人主页")
    }

    private fun gotoKoubeiDetail() {
        //跳转带货口碑详情
        ARouter.getInstance().build("/mall/ReputationActivity").navigation()
    }

    private fun setPriceTabText() {
        val priceTab = binding.tabSort.getTabAt(3)
        priceTab?.text = if (priceSortDesc) "价格↓" else "价格↑"
    }

    private fun notifySortChanged() {
        val recommendFragment = fragments[1] as? GoodsRecommendFragment
        recommendFragment?.sortGoods(currentSortType, priceSortDesc)
    }

}










